package com.basin.common.core.response;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import org.apache.http.HttpStatus;

import java.io.Serial;
import java.io.Serializable;

/**
 * 统一响应对象
 *
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Getter
@JsonInclude(JsonInclude.Include.NON_NULL)
public final class ResponseResult<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    private ResponseResult() {
    }

    private ResponseResult(int code, String message) {
        this.code = code;
        this.message = message;
    }

    private int code;

    private String message;

    private T data;

    private void setData(T data) {
        this.data = data;
    }

    private void setMessage(String message) {
        this.message = message;
    }

    private void setCode(int code) {
        this.code = code;
    }

    private static <T> ResponseResult<T> init(boolean isSuccess) {
        return isSuccess ? new ResponseResult<>(HttpStatus.SC_OK, "请求成功") : new ResponseResult<>(HttpStatus.SC_INTERNAL_SERVER_ERROR, "请求失败");
    }

    public static <T> ResponseResult<T> success() {
        return ResponseResult.init(true);
    }

    public static <T> ResponseResult<T> fail() {
        return ResponseResult.init(false);
    }

    public static <T> ResponseResult<T> success(T data) {
        ResponseResult<T> responseResult = ResponseResult.success();
        responseResult.setData(data);
        return responseResult;
    }

    public static <T> ResponseResult<T> fail(String message) {
        ResponseResult<T> responseResult = ResponseResult.fail();
        responseResult.setMessage(message);
        return responseResult;
    }

    public static <T> ResponseResult<T> fail(Integer code, String message) {
        ResponseResult<T> responseResult = ResponseResult.fail(message);
        responseResult.setCode(code);
        return responseResult;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
